﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace LaserHarp
{
    // The BeamConfig class stores configuration data for serialization to an XML file

    [Serializable()]
    public class BeamConfig : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string name;
        public int nBeams;
        public int midiOutID;
        public int Y1;
        public int Y2;
        public int[] notes;
        public int[] posX1;
        public int[] posX2;

        public string ConfigName 
        { 
            get { return name; }
            set 
            { 
                name = value;
                this.NotifyPropertyChanged("ConfigName");
            }
        }

        private void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    public class ConfigManager
    {
        //The ConfigManager class is used to combine several BeamConfig classes into a BindingList, 
        // whcih can be read from or written to a XML file.
        // The BindingList type allows the configuration list to be bound to a ListBox control in the GUI.

        public void SaveConfig(BindingList<BeamConfig> cfg)
        {
            //Config file location hardcoded for now. Needs to be made user definable.
            string filepath = "D:\\Temp\\BeamConfigs.xml";
            XmlWriterSettings xSettings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                Indent = true,
                NewLineChars = Environment.NewLine,
                NewLineOnAttributes = false,
                ConformanceLevel = ConformanceLevel.Document
            };
            XmlWriter xw = XmlWriter.Create(filepath, xSettings);
            XmlSerializer ser = new XmlSerializer(typeof(BindingList<BeamConfig>));
            ser.Serialize(xw, cfg);
            xw.Close();
        }

        public BindingList<BeamConfig> LoadConfig()
        {
            BindingList<BeamConfig> cfg = null;
            string filepath = "D:\\Temp\\BeamConfigs.xml";
            XmlSerializer ser = new XmlSerializer(typeof(BindingList<BeamConfig>));
            if (File.Exists(filepath))
            {
                XmlReader xr = XmlReader.Create(filepath);
                cfg = (BindingList<BeamConfig>)ser.Deserialize(xr);
                xr.Close();
            }
            return cfg;
        }
    }
}
